/**
 * Created with Vim7.3 Mac
 * @fileOverview :
 * @author : Lyle lylechen2014@gmail.com
 * @since : 2016-06-30 18:10:57
 * @filename : src/components/register.js
 * @version :
 * @description :
 */
import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  TouchableOpacity,
  DatePickerIOS,
  ScrollView,
  Picker,
  ActivityIndicator
} from 'react-native';

import Icon from 'react-native-vector-icons/Ionicons'
import Login from './login'
import Country from '../common/country'
import State from '../common/state'
import PickerModal from '../common/pickerModal'
import Tips from '../common/tips'
import RegisterB from './registerB'
import ServiceAgreement from './serviceAgreement'

let tempDate,tempDisability=[],tempCountry,tempState,checkBool=false;

class Register extends Component {

  constructor(props) {
      super(props);
      this.state = {
         gender:1,
         match_gender:2,
         datePickerModalVisible:false,  
         chooseDate:null,
         disability:[],   
         disabilityPickerModalVisible:false,
         country:null,  
         countryPickerModalVisble:false,
         countryCallback:false,  
         countryType:1,
         statePickerModalVisble:false,
         state:null,
         stateCallback:false,
         zipCode:null,
         argee : false,
         zipCodeError : false,
         zipCodeBool: false,
      };
  }

  componentDidMount() {
      Share.getCountryList({callback:()=> this.setState({countryCallback:true})});
  }

  shouldComponentUpdate(props,state) {
     this.checkContiune(state);
     return true;
  }

  callbackCountry () {
      this.setState({countryCallback:true});
  }

  domGender(key) {
      let jsx = null,items = [],data = JSON.parse(Store.local_gender);
      //data.push({"value":"4","label":"Man"});
      for (var i in data) {
          let value= data[i].value;
          let ViewStyle = i > 0 ? styles.genderButtonView : null;
          items[i] = (<View key={value} style={ViewStyle}><Text suppressHighlighting={true} style={this.getGenderStyle(key,value)} onPress = {()=>{this.changeState(key,value)}}> {data[i].label} </Text></View>);
      }        
      return (items);
  }

  domDatePickerModal() {
      let jsx = null;
      if (this.state.datePickerModalVisible) {
          jsx = <PickerModal
                 navTitle='Choose time'
                 modalVisible={this.state.datePickerModalVisible}
                 onPickerModalCancel = {()=>{this.changeState('datePickerModalVisible',false)}}
                 onPickerModalSave = {()=>{this.saveDate()}}
                >              
                <DatePickerIOS
                  date = {this.state.chooseDate ? this.state.chooseDate : new Date(Utils.lastNumMonth(216))}
                  mode = "date"
                  onDateChange={(d)=>{this.changeDate(d)}}
                  minimumDate={new Date(Utils.lastNumMonth(1188))}
                  maximumDate={new Date(Utils.lastNumMonth(216))}
                />
                </PickerModal>
      }
      return (jsx);
  }

  domLWPickerModal(tempDisability) {
      let jsx = null,
          items = this.makeLWItems(tempDisability);
      if (this.state.disabilityPickerModalVisible) {
          jsx = <PickerModal
                 navTitle='LivingWith'
                 modalVisible={this.state.disabilityPickerModalVisible}
                 onPickerModalCancel = {()=>this.onLWPickerModalCancel()}
                 onPickerModalSave = {()=>this.onLWPickerModalSave()}
                >
                <View style={styles.scrollBox}>
                <ScrollView>
                  {items}
                </ScrollView>
                </View>
                </PickerModal>
      }
      return (jsx);
  }

  makeLWItems(tempDisability){
      var items = [],data = JSON.parse(Store.local_disability);
      for (var i in data) {
          let value = data[i].value;
          if (_.indexOf(tempDisability,data[i].value) > -1) {
              items[i] = (
                      <TouchableOpacity style={styles.itemView} activeOpacity={1} key={value} onPress={()=>this.onLWChange(value)}>
                        <Text suppressHighlighting={true} style={[styles.itemText,styles.itemTextAction]}>{data[i].label}</Text>
                        <Icon name="ios-checkmark" style={styles.itemTextAction} size={40}/> 
                      </TouchableOpacity>
              );
          } else {
              items[i] = (
                       <TouchableOpacity activeOpacity={1} key={value} onPress={()=>this.onLWChange(value)}>
                          <View style={styles.itemView}> 
                          <Text suppressHighlighting={true} style={styles.itemText}>{data[i].label}</Text>
                          </View>
                       </TouchableOpacity>
              );
          }  
      }
      return items;
  }

  domCountryPickerModal() {  
      let jsx = null;
      if (this.state.countryPickerModalVisble) {
          jsx = <PickerModal
                 navTitle='Country'
                 modalVisible={this.state.countryPickerModalVisble}
                 onPickerModalCancel = {()=>this.onCountryPickerModalCancel()}
                 onPickerModalSave = {()=>this.onCountryPickerModalSave()}
                >
                <View style={styles.scrollBoxCountry}>            
                    <Country callbackParent = {this.onCountryChange}  country = {this.state.country}/>              
                </View>
                </PickerModal>
      }
      return (jsx);
  }

  domStatePickerModal() {  
      let jsx = null;
      if (this.state.statePickerModalVisble) {
          jsx = <PickerModal
                 navTitle='State'
                 modalVisible={this.state.statePickerModalVisble}
                 onPickerModalCancel = {()=>this.onStatePickerModalCancel()}
                 onPickerModalSave = {()=>this.onStatePickerModalSave()}
                >
                <View style={styles.scrollBox}>            
                    <State callbackParent = {this.onStateChange}  state = {this.state.state}  country = {this.state.country} />              
                </View>
                </PickerModal>
      }
      return (jsx);
  }
  
  makeCountryTypeDom() {
      let jsx = null;
      if (this.state.countryType == 2) {
            if (this.state.stateCallback) {
              jsx = <View style={styles.inputText}>
                      <TouchableOpacity onPress={()=>this.showState()}>
                      <TextInput
                            style={styles.input}
                            placeholder="State"
                            numberOfLines={1}
                            textAlign="left"
                            editable={false}
                            value = {(this.state.state ? this.getStateLabel(this.state.state) :null)}
                            />
                      <Image style={styles.imgbg} source={require('../img/date.png')} />
                      </TouchableOpacity>
                    </View>
            } else {
              Share.getStateList({country:this.state.country,callback:()=> this.setState({stateCallback:true})});
            }
      } else {
            jsx = <View style={styles.inputText}  >
                    <TextInput
                          autoCapitalize = "none"
                          autoCorrect={false}
                          style={this.state.zipCodeError ? [styles.input,styles.inputError] : styles.input}
                          placeholder="Zip Code"   
                          textAlign="left"
                          onChangeText={(value) => this.onZipCodeSave(value)}
                          onFocus = {()=>{this.inputFocusBlur('tabA',-100)}}
                          onBlur={()=>{this.inputFocusBlur('tabA',0)}}
                          /*keyboardType = {'numeric'}*/
                          />
                    <Image style={styles.imgbg} source={require('../img/date.png')} />
                  </View>
      } 
      return (jsx);
  }

  postLoading() {
      let jsx = null;
      if (this.state.zipCodeBool) {
          jsx = <ActivityIndicator size="small" color="#fff"/>
      } else {
          jsx = <TouchableOpacity activeOpacity={this.getContinueActiveOpacity()} onPress={()=>this.continue()} >
                <Text suppressHighlighting={true} style={styles.buttonText}> Continue </Text>
                </TouchableOpacity>
      }
      return (jsx);
  }

  render() {

    let datePickerModal = this.domDatePickerModal();
    let lwPickerModal = this.domLWPickerModal(tempDisability);
    let countryPickerModal = this.state.countryCallback ? this.domCountryPickerModal(tempCountry) : null;
    let statePickerModal = this.state.stateCallback ? this.domStatePickerModal(tempCountry) : null;
    let countryTypeText = this.makeCountryTypeDom();
    let argeeIcon  = this.state.argee ? <Icon name='md-checkmark' style={styles.iconIn} size= {16}/> : null;
    let postButton = this.postLoading();

    return (
      <View style={styles.container}>
          <ScrollView ref='tabA' style = {styles.tabA}>

               <View style={styles.tabA_des}>
                 <View style={styles.tabA_line} />
                 <Text suppressHighlighting={true} style={styles.tabA_text}>
                      {Lang.reg_gendeDes}
                 </Text>
               </View>

               <View style={styles.tabA_myGender}>
                    <Text suppressHighlighting={true} style={styles.tabA_myGenderText}>
                         {Lang.reg_gender}
                    </Text>
                    <View style={styles.tabA_genderTab}>            
                        {this.domGender('gender')}
                    </View>
               </View>

                <View style={styles.tabA_myGender}>
                    <Text suppressHighlighting={true} style={styles.tabA_myGenderText}>
                        {Lang.reg_matchGender}
                    </Text>
                    <View style={styles.tabA_genderTab}>
                        {this.domGender('match_gender')}
                    </View>
               </View>

               <View style={styles.tabA_des}>
                    <View style={styles.tabA_line} />
                    <Text suppressHighlighting={true} style={styles.tabA_text}>
                      {Lang.reg_details}
                    </Text>
               </View>

               <View style={styles.inputText} >
                    <TouchableOpacity onPress={()=>{this.showDate()}}>
                    <TextInput
                            style={styles.input}
                            placeholder="Birthday"
                            numberOfLines={1}
                            textAlign="left"
                            editable={false}
                            value = {(this.state.chooseDate ? Utils.dateFormat(this.state.chooseDate,'yyyy-MM-dd') : null)}
                            />
                    <Image style={styles.imgbg} source={require('../img/date.png')} />
                    </TouchableOpacity>
               </View>

               <View style={styles.inputText}  >
                    <TouchableOpacity onPress={()=>this.showLivingWith()}>
                    <TextInput
                            style={styles.input}
                            placeholder="Living with"
                            numberOfLines={1}
                            textAlign="left"
                            editable={false}
                            value = {(this.state.disability.length > 0 ? this.state.disability.length.toString():null)}
                            />
                    <Image style={styles.imgbg} source={require('../img/date.png')} />
                    </TouchableOpacity>
               </View>
              
               <View style={styles.inputText}  >
                    <TouchableOpacity onPress={()=>this.showCountryWith()}>
                    <TextInput
                            autoCapitalize = "none"
                            autoCorrect={false}
                            style={styles.input}
                            placeholder="Country"
                            textAlign="left"
                            editable={false}
                            value = {(this.state.country  ? this.getCountryLabel(this.state.country) :null)}
                            />
                    <Image style={styles.imgbg} source={require('../img/date.png')} />
                    </TouchableOpacity>
               </View>

               {countryTypeText}

               <View style={styles.serviceAgreementArea}>
                   <TouchableOpacity  activeOpacity={1}  onPress={()=>this.argeeService()} >
                   <View style={styles.iconOut}>
                     {argeeIcon}
                   </View>
                   </TouchableOpacity>
                   <Text suppressHighlighting={true} onPress={()=>this.argeeService()} style={styles.saText} numberOfLines={5}>{Lang.reg_service_a}<Text suppressHighlighting={true} onPress={()=>this.gotoService()} style={styles.saTextLink}>{Lang.reg_service_b}</Text> {Lang.reg_service_c} <Text suppressHighlighting={true} onPress={()=>this.gotoPP()} style={styles.saTextLink}>{Lang.reg_service_d}</Text>.</Text>
                  
               </View>

               <View ref='reg_continue' style={styles.button}>
                  {postButton}
               </View>

               <View>
                   <Text suppressHighlighting={true} style={styles.loginText}> {Lang.reg_loginText} 
                         <Text suppressHighlighting={true} onPress={()=>this.gotoLogin()} style={styles.loginTextButton}> Log in </Text> 
                    </Text>
               </View>


 
               {/*
               <View style={styles.inputText}  >
                  <TouchableOpacity onPress={()=>this.gotoMyProfile()}>
                  <Text> go to myProfile </Text> 
                  </TouchableOpacity>
               </View>
              
              <View style={styles.inputText}  >
                  <TouchableOpacity onPress={()=>this.gotoRegisterB()}>
                  <Text> go to RegisterB </Text> 
                  </TouchableOpacity>
               </View>
               */}
                
          </ScrollView>
          <Tips ref='tips'/>
          {datePickerModal}
          {lwPickerModal}
          {countryPickerModal}
          {statePickerModal}
      </View>
    );
  }

  getGenderStyle(key,value) {
        let arr = [styles.genderButton];
        if (this.state[key] == value ) {
            arr = [styles.genderButton,styles.genderAction]
        }
        return arr;
    }

    changeState(key,value) {
        let obj = {};
        obj[key] = value;
        this.setState(obj);
    }

    showDate() {
        this.setState({datePickerModalVisible: true}); 
        tempDate =  _.clone(this.state.chooseDate ? this.state.chooseDate : new Date(Utils.lastNumMonth(216)));
    }

    saveDate() {
        this.setState({chooseDate:tempDate,datePickerModalVisible: false});
    }

    changeDate (date) {
        tempDate = new Date(date);
    }

    showLivingWith() {
        this.setState({disabilityPickerModalVisible: true}); 
        tempDisability = _.clone(this.state.disability);
    }

    onLWPickerModalCancel () {
        this.setState({disabilityPickerModalVisible: false});
    }

    onLWPickerModalSave() {
        this.setState({disability:tempDisability,disabilityPickerModalVisible: false});
    }

    onLWChange(data) {
        if (_.indexOf(tempDisability,data) > -1) {
            _.pull(tempDisability,data);
        } else {
            tempDisability.push(data);
        }
        this.forceUpdate();
    }

    showCountryWith() {
        this.setState({countryPickerModalVisble: true});
    }

    onCountryPickerModalCancel() {
        this.setState({countryPickerModalVisble: false});
    }

    onCountryPickerModalSave() {
        if(_.indexOf([0,31,180],parseInt(tempCountry)) == -1) {         
            this.setState({countryType:2,country:tempCountry,countryPickerModalVisble:false,zipCode:null,state:null,stateCallback:false});
        } else {
            this.setState({countryType:1,country:tempCountry,countryPickerModalVisble:false,zipCode:null,state:null,stateCallback:false});
        }
    }

    onCountryChange(data) {
        tempCountry = data;
    }

    onStateChange(data) {
        tempState = data;
    }

    showState() {
        this.setState({statePickerModalVisble: true});
    }

    onStatePickerModalCancel() {
        this.setState({statePickerModalVisble: false});
    }

    onStatePickerModalSave() {
        this.setState({statePickerModalVisble:false,zipCode:null,state:tempState});
    }

    onZipCodeSave(value) {
        this.setState({zipCode:value,state:null,zipCodeError:false});
    }

    getCountryLabel(value) {
        if (this.state.countryCallback && value !== null) {
            let data = JSON.parse(Store.local_country);
            let obj = _.find(data,{value:value},'label');
            return obj.label;
        }
    }

    getStateLabel(value) {
        if (this.state.stateCallback && value !== null) {
            let dataObj = JSON.parse(Store.local_state_list);
            let data = dataObj[this.state.country];
            let obj = _.find(data,{value:value},'label');
            return obj.label;
        }
    }

    argeeService() {
        if (this.state.argee) {
            this.setState({argee:false});
        } else {
            this.setState({argee:true});
        }
    }

    gotoService() {
        console.log('gotoService');
        Utils.navJumpTo(this.props.navigator,{name:"ServiceAgreement",component:ServiceAgreement,title:'ServiceAgreement'});
    }

    checkContiune(state) {
        let bool = true;

        if (state.gender == null) {
            bool = false;
        } 
       
        if (state.match_gender == null) {
            bool = false;
        }            

        if (state.chooseDate == null) {
            bool = false;
        }

        if (_.isEmpty(state.disability)) {
            bool = false;
        }

        if (state.country == null) {
            bool = false;
        } else {
            if (_.indexOf([0,31,180],parseInt(state.country)) == -1) {
                if (state.state == null) {
                    bool = false;
                }  
            } else {
               if (state.zipCode == null || _.trim(state.zipCode) == '') {
                    bool = false;
               } 
            }
       }

       if(state.argee == false) {
          bool = false;
       }

       checkBool = bool;

       let color = bool ? '#56ade0' : '#999';
       this.refs['reg_continue'].setNativeProps({style:{backgroundColor: color}});

    }

    getContinueActiveOpacity() {
       return checkBool ? 0 : 1;
    }

    continue() {        
        if (checkBool && !this.state.zipCodeBool) {
            let obj = this.getFristData();
            this.setState({zipCodeBool:true})
            this.checkZipCode(obj);
        }
    }

    getFristData() {
        let obj = {},
            date = new Date(this.state.chooseDate);
        obj.gender = this.state.gender;
        obj.match_gender =this.state.match_gender;
        obj.age = Utils.age(date.getFullYear());
        obj.age_year = date.getFullYear();
        obj.age_month = date.getMonth() + 1;
        obj.age_day = date.getDate();
        obj.r_country = this.state.country;
        obj.r_zip = this.state.zipCode;
        obj.type = 11;//default !mm
        obj.disability = Utils.getMultipleData(this.state.disability);
        return obj;
    }

    checkZipCode(obj) {
        let that = this;
        Share.fetchMain({
            url : 'check_zip',
            data: obj,
            callback : function(data) {
                if (typeof(data.errcode) !== 'undefined') {
                    let objError = {type: 'error', msg: data.errmsg };
                    that.refs['tips'].showTips(objError);
                    that.setState({zipCodeError:true,zipCodeBool:false});
                } else {
                    console.log('registerB');
                    Share.setStorage('register',JSON.stringify(obj),function(){
                        Utils.navJumpTo(that.props.navigator, { name: "RegisterB", component: RegisterB, title: 'Register'});
                    });
                }  
            }
        });
    }

    gotoPP() {
        console.log('gotoPP');
    }

    gotoLogin() {
        Utils.navJumpTo(this.props.navigator, { name: "Login", component: Login, title: 'Log In'});
    }

    inputFocusBlur(id,num) {
        this.refs[id].setNativeProps({style:{marginTop:num}});
    }

    gotoMyProfile() {
        Utils.navJumpTo(this.props.navigator, { name: "MyProfile", component: MyProfile, title: 'MyProfile',navBarType: 1});
    }

    gotoRegisterB() {
        Utils.navJumpTo(this.props.navigator, { name: "RegisterB", component: RegisterB, title: 'Register'});
    }
}

const styles = StyleSheet.create(Css.RegisterStyle);

export default Register;

